//
//  AppDelegate.m
//  MyWeChat
//
//  Created by 蔡欣东 on 15/10/5.
//  Copyright © 2015年 蔡欣东. All rights reserved.
//

#import "AppDelegate.h"

#import "FriendListViewController.h"
#import "ViewController2.h"
#import "ViewController3.h"
#import "LoginViewController.h"


@interface AppDelegate ()<XMPPStreamDelegate>

@end




@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self setupTabbarController];
    self.window.rootViewController = _tabbarController;
    [self.window makeKeyAndVisible];
    
    if ([[NSUserDefaults standardUserDefaults] stringForKey:USERNAME] == nil) {
        NSLog(@"1");
        [self showLoginView:false];
    }else{
        NSLog(@"我的账号是%@",[[NSUserDefaults standardUserDefaults] stringForKey:USERNAME]);
        NSLog(@"我的密码是%@",[[NSUserDefaults standardUserDefaults] stringForKey:PASSWORD]);
        NSLog(@"2");
        [self login];
    }
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
}
#pragma mark - 建立tabbarcontroller
-(void)setupTabbarController{
    
    
    _tabbarController = [[UITabBarController alloc]init];
    
    FriendListViewController* c1 = [[FriendListViewController alloc]init];
    
    c1.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemTopRated tag:1];
    
    UINavigationController* nvc = [[UINavigationController alloc]initWithRootViewController:c1];
    nvc.navigationBarHidden = YES;
    ViewController2* c2 = [[ViewController2 alloc]init];
    
    c2.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemContacts tag:2];
    
    ViewController3* c3 = [[ViewController3 alloc]init];
    
    c3.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemMore tag:3];
    
    _tabbarController.viewControllers = @[nvc,c2,c3];
    
}
#pragma mark - 显示聊天框
-(void)showLoginView:(BOOL) animated{
   UIStoryboard* mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
   
   LoginViewController* vc =  [mainStoryboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
    [_tabbarController presentViewController: vc animated:animated completion:nil];
    
}
-(void)login{
    [self setupStream];
    [self connect];
}
#pragma mark - xmpp
-(void)setupStream{
    NSLog(@"setupstream");
    _xmppStream1 = [[XMPPStream alloc]init];
    [_xmppStream1 addDelegate:self delegateQueue:dispatch_get_main_queue()];
}
-(void)teardownStream{
    [_xmppStream1 removeDelegate:self];
    _xmppStream1 = nil;
}
-(BOOL)connect{
    
    if ([_xmppStream1 isConnected]==YES) {
        NSLog(@"is connect");
        return YES;
    }
    
    NSString* localJID = [[NSUserDefaults standardUserDefaults] stringForKey:USERNAME];
    NSString* localPassword = [[NSUserDefaults standardUserDefaults] stringForKey:PASSWORD];
    
    if (localJID == nil||localPassword == nil) {
        NSLog(@"账号或密码为空，连接不成功");
        return NO;
    }
    _xmppStream1.myJID = [XMPPJID jidWithString:localJID];
    //服务器的地址
    _xmppStream1.hostName = SERVERADD;
    
    if ([_xmppStream1 connectWithTimeout:5000 error:nil] == NO) {
        NSLog(@"连接失败，检查网络");
        return NO;
    }
    return YES;
}
-(void)loginOff{
    [self goOffline];
    [_xmppStream1 disconnect];
}
#pragma mark - xxmp delegate
-(void)xmppStreamDidConnect:(XMPPStream *)sender{
    
    NSLog(@"已经连接");
    //认证
    if ([_xmppStream1 authenticateWithPassword:[[NSUserDefaults standardUserDefaults] stringForKey:PASSWORD ] error:nil]) {
        NSLog(@"认证成功");
    }else{
        NSLog(@"认证失败");
    }
    }
-(void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error{
    NSLog(@"错误是%@",error);
}
//认证成功
-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
    NSLog(@"已经认证成功");
    [self goOnline];
}
//登录上线成功返回信息（好友上下线也会执行这个方法）
-(void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence{
    //NSLog(@"%@get friend",presence);
    //获取好友列表
    if (sender.myJID.user != [presence from].user) {
        NSString* tmpName = [NSString stringWithFormat:@"%@@%@",[presence from].user,[presence from].domain];
        UserInfo* myfriend = [[UserInfo alloc]initWithId:1 andName:tmpName];
        
        NSString* presenceType=[presence type];
        
        if ([presenceType isEqual:@"available"]) {
            myfriend.isOnline = YES;
        }else if([presenceType isEqual:@"unavailable"]){
            myfriend.isOnline = NO;
            
        }
        NSLog(@"my friend is %@",myfriend.name);
        [_presenceDelegate presenceDidChange:myfriend];
    }
}
//收到消息
-(void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{
    if ([message isChatMessage]) {
        NSLog(@"收到消息是%@",message);
        
        MessageInfo* chatMessage = [[MessageInfo alloc]init];
        
        NSString* tmpName = [NSString stringWithFormat:@"%@@%@",[message from].user,[message from].domain];
        chatMessage.user = [[UserInfo alloc]initWithId:1 andName:tmpName];
        
        NSString* tmpTarget = [NSString stringWithFormat:@"%@@%@",[message to].user,[message to].domain];
        chatMessage.target = [[UserInfo alloc]initWithId:1 andName:tmpTarget];
        
        if ([message elementsForName:@"composing"]!=nil) {
            chatMessage.messageStatue = (MessageStatue) compose;
        }
        if ([message elementsForName:@"delay"]!=nil) {
            chatMessage.messageStatue = (MessageStatue) delay;
        }
        
        if ([message body]!=nil) {
            chatMessage.messageBody = [message body];
        }
        
        if ([message elementsForName:@"body"]!=nil) {
            //chatMessage.messageBody = [NSString stringWithFormat:@"%@",[message elementsForName:@"body"] ];
        }

            [_messageDelegate didRecieveMessage:chatMessage];
        [_messageInFriendListDelegate didRecieveMessageInFriendList:chatMessage];
     
        
    }
}
#pragma mark - 上下线
-(void)goOnline{
    XMPPPresence* presence = [[XMPPPresence alloc]init];
    
    //NSString* domain =  _xmppStream1.myJID.domain;
    [_xmppStream1 sendElement:presence];
}
-(void)goOffline{
    XMPPPresence* presence = [XMPPPresence presenceWithType:@"unavailable"];
    [_xmppStream1 sendElement:presence];
}
@end
